package db

import (
	"com.jiaguyu/logger"
	"com.jiaguyu/model"
	"database/sql"

	"github.com/jmoiron/sqlx"
)

func GetAnswerIdList(question_id int64, offset, limit int64) (answerIdList []int64, err error) {
	sqlStr := `select 
                    answer_id 
                   from question_answer_rel 
                   where question_id=? 
                     order by id asc limit?,?`
	err = DB.Select(&answerIdList, sqlStr, question_id, offset, limit)
	if err != nil {
		return
	}
	return
}

//问题回答的list
func MGetAnswerList(answerIds []int64) (answerList []*model.Answer, err error) {
	if len(answerIds) == 0 {
		return
	}
	sqlstr := `select answer_id,content,comment_count,voteup_count,author_id,status,can_comment,create_time,update_time
                  from answer where answer_id in(?)`
	var answerTempArr []interface{}
	for _, answerId := range answerIds {
		answerTempArr = append(answerTempArr, answerId)
	}
	//转换数组
	query, args, err := sqlx.In(sqlstr, answerTempArr)
	if err != nil {
		logger.Error("SQLX 出问题%v、n", err)
		return
	}
	err = DB.Select(&answerList, query, args...)

	//有可能数据 结构中为空
	if err == sql.ErrNoRows {
		err = nil
		return
	}
	if err != nil {
		logger.Error("查询失败err:%v", err)
		return
	}
	return
}

//获取计算总数
func GetAnswerCount(question_id int64) (answerCount int64, err error) {
	sqlStr := `select 
                    Count(answer_id) 
                   from question_answer_rel 
                   where question_id=?`
	err = DB.Get(&answerCount, sqlStr, question_id)
	if err != nil {
		logger.Error("查询count失败err:%v", err)
		return
	}
	return
}

func UpdateAnswerCount(answer_id int64) (err error) {
	sqlStr := `update answer set voteup_count=voteup_count+1 where answer_id =?`
	_, err = DB.Exec(sqlStr, answer_id)
	if err != nil {
		logger.Error("更新点赞数据失败%v", err)
		return
	}
	return
}
